package com.dacd.sdl.sendclient.activity;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.Nullable;
import android.view.KeyEvent;
import android.widget.LinearLayout;

import com.dacd.sdl.sendclient.EventBean.UnlockEvent;
import com.dacd.sdl.sendclient.EventBean.UploadEvent;
import com.dacd.sdl.sendclient.R;
import com.dacd.sdl.sendclient.activity.Base.BaseActivity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by soule on 2018/2/27.
 */

/**
 * 锁屏不断保存图片的界面
 */
public class LockScreenActivity extends BaseActivity {

    private LinearLayout uploadLayout;//上传的layout
    private boolean isWhite;
    private Timer timer;
    private Handler handler;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lock_screen);
        handler = new Handler(Looper.getMainLooper());
        uploadLayout = (LinearLayout) findViewById(R.id.als_upload_layout);
        uploadLayout.setBackgroundColor(Color.WHITE);
        isWhite = true;
        timer = new Timer();
        timer.schedule(new MyTimeTask(), 1000, 2000);
    }

    class MyTimeTask extends TimerTask {

        @Override
        public void run() {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    uploadLayout.setDrawingCacheEnabled(true);
                    if (isWhite) {
                        uploadLayout.setBackgroundColor(Color.BLUE);
                        isWhite = false;
                    } else {
                        uploadLayout.setBackgroundColor(Color.WHITE);
                        isWhite = true;
                    }
                    uploadLayout.buildDrawingCache();
                    Bitmap bp = Bitmap.createBitmap(uploadLayout.getDrawingCache());
                    uploadLayout.setDrawingCacheEnabled(false);
                    UploadEvent uploadEvent = new UploadEvent();
                    uploadEvent.setUploadBm(bp);
                    EventBus.getDefault().post(uploadEvent);
                }
            });
        }
    }

    @Subscribe
    public void onEventMainThread(UnlockEvent unlockEvent) {
        if (unlockEvent != null) {
            finish();
        }
    }

    @Override
    protected void onDestroy() {//取消注册事件通知
        handler.removeCallbacksAndMessages(null);
        super.onDestroy();
        if (timer != null) {
            timer.cancel();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }
}
